package erz.printing.police.print;

import android.content.Context;
import android.os.Build;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class PrintWebView {
    private WebView mWebView;
    private Context mContext;
    private String htmlFile;

    public PrintWebView(Context context, String htmlFile) {
        this.mContext = context;
        this.htmlFile = htmlFile;
    }

    public void doPrint() {
        mWebView = new WebView(mContext);
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            public void onPageFinished(WebView view, String url) {
                createWebPrintJob(view);
                mWebView = null;
            }
        });
        mWebView.loadUrl(htmlFile);
    }

    private void createWebPrintJob(WebView webView) {
        PrintManager printManager = (PrintManager)mContext.getSystemService(Context.PRINT_SERVICE);
        String jobName = "html document";
        PrintDocumentAdapter printAdapter;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            printAdapter = webView.createPrintDocumentAdapter(jobName);
        }
        else {
            printAdapter = webView.createPrintDocumentAdapter();
        }
        printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());
    }
}
